package org.example.onlinejudge.controller.api;

import org.example.onlinejudge.model.Permission;
import org.example.onlinejudge.model.Role;
import org.example.onlinejudge.model.User;
import org.example.onlinejudge.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 用户权限API控制器
 */
@RestController
@RequestMapping("/api/user-permissions")
@PreAuthorize("hasRole('0')")
public class UserPermissionApiController {

    @Autowired
    private UserService userService;

    /**
     * 获取用户的权限信息
     */
    @GetMapping("/{userId}")
    @PreAuthorize("hasAuthority('user:view')")
    public Map<String, Object> getUserPermissions(@PathVariable Long userId) {
        User user = userService.findById(userId).orElseThrow();
        
        Map<String, Object> result = new HashMap<>();
        
        // 角色权限
        List<Map<String, String>> rolePerms = new ArrayList<>();
        for (Role role : user.getRoles()) {
            for (Permission perm : role.getPermissions()) {
                Map<String, String> permMap = new HashMap<>();
                permMap.put("id", String.valueOf(perm.getId()));
                permMap.put("code", perm.getPermCode());
                permMap.put("name", perm.getPermName());
                permMap.put("source", "角色：" + role.getRoleName());
                rolePerms.add(permMap);
            }
        }
        
        // 直接权限
        List<Map<String, String>> directPerms = new ArrayList<>();
        for (Permission perm : user.getPermissions()) {
            Map<String, String> permMap = new HashMap<>();
            permMap.put("id", String.valueOf(perm.getId()));
            permMap.put("code", perm.getPermCode());
            permMap.put("name", perm.getPermName());
            directPerms.add(permMap);
        }
        
        result.put("rolePermissions", rolePerms);
        result.put("directPermissions", directPerms);
        
        return result;
    }
}

